package com.whpost.service.service.stamp;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.config.Wdpz;
import com.whpost.service.dao.stamp.StampHdMapper;
import com.whpost.service.dao.stamp.StampXmMapper;
import com.whpost.service.dao.t.TDelDao;
import com.whpost.service.entity.stamp.StampHd;
import com.whpost.service.entity.stamp.StampXm;
import com.whpost.service.entity.t.TCzy;
import com.whpost.service.entity.t.TDel;
import com.whpost.service.entity.t.TRole;
import com.whpost.service.entity.t.TXzjg;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.BaseServices;
import com.whpost.service.service.t.FileService;
import com.whpost.service.service.t.TApiNonceService;
import com.whpost.service.tools.QRCodeGenerator;
import com.whpost.service.tools.ToolBean;
import com.whpost.service.tools.Url;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StampXmServices extends BaseServices {

    @Resource
    private StampXmMapper stampXmMapper;
    @Resource
    private StampHdMapper stampHdMapper;
    @Resource
    private TApiNonceService tApiNonceService;
    @Resource
    private Wdpz wdpz;
    @Resource
    private FileService fileService;
    @Resource
    private TDelDao tDelDao;

    @Override
    public ResultInfo info(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            TCzy tCzy = new TCzy();
            tCzy = gettCzyDao().selectById(loginId);

            Map<String,Object> infoMap = new HashMap<>();

            String id="";
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            String lx="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }

            if ("1".equals(lx)){
                StampXm stampXm = new StampXm();
                if(StringUtils.isEmpty(id)){
                    return new ResultInfo(500,"修改信息丢失！",null);
                }
                try {
                    id = Url.decrypt(id);
                } catch (Exception e) {
                    throw new RuntimeException("修改信息丢失！");
                }
                stampXm = stampXmMapper.selectById(id);
                if (null!=stampXm){
                    stampXm.setUrlId(ToolBean.getEncode(stampXm.getId()));
                    stampXm.setId(null);
                }
                infoMap.put("stampXm",stampXm);
            }

            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",infoMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            TCzy tCzy = gettCzyDao().selectById(loginId);
            String curpage = "",pagesize="",cxmc="";
            QueryWrapper<StampXm> queryWrapper = new QueryWrapper<>();
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("cxmc")) {
                cxmc = jsonObject.getString("cxmc");
            }

            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "10";

            Page<StampXm> page = new Page<>( Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            ListInfo<StampXm> stampXmListInfo = new ListInfo<>();
            if (!StringUtils.isEmpty(cxmc))
            {
                queryWrapper.like("name",cxmc);
            }
            queryWrapper.eq("t_xzjg_id",tCzy.getXzjgId());

            queryWrapper.orderByDesc("id");

            IPage<StampXm> stampXmIPage = stampXmMapper.selectPage(page,queryWrapper);

            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(stampXmIPage.getTotal());
            pageInfo.setCurPage(stampXmIPage.getCurrent());
            pageInfo.setPageSize(stampXmIPage.getSize());
            pageInfo.setPageTotal(stampXmIPage.getPages());

            stampXmListInfo.setPageInfo(pageInfo);

            List<StampXm> stampXmList = stampXmIPage.getRecords();

            // 循环遍历 List 并改变每个对象的 age 属性
            for (StampXm stampXm : stampXmList) {
                stampXm.setUrlId(ToolBean.getEncode(stampXm.getId()));
                stampXm.setId(null);
            }

            stampXmListInfo.setListInfo(stampXmList);
            stampXmListInfo.setUserId(loginId);

            //查询条件的值
            Map<String,Object> cxtjMap = new HashMap<>();
            cxtjMap.put("cxmc",cxmc);

            //返回前端的内容
            Map<String,Object> rtnMap = new HashMap<>();
            rtnMap.put("cxjg",stampXmListInfo);
            rtnMap.put("cxtj",cxtjMap);

            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",rtnMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo save(String loginId, List<MultipartFile> file, String data) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            JSONObject jsonObject = getDataStr(data,loginId);
            String lx="",id="",nonce_ms="",nonce_zhi="",xmmc="",xsmc="",dbsy="",jzrq="",xmxx_id="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("xmmc")) {
                xmmc = jsonObject.getString("xmmc");
            }
            if (jsonObject.containsKey("xsmc")) {
                xsmc = jsonObject.getString("xsmc");
            }
            if (StringUtils.isEmpty(lx) || (StringUtils.isEmpty(id) && "1".equals(lx))){
                return new ResultInfo(500,"关键参数信息丢失！",null);
            }
            if (StringUtils.isEmpty(xmmc) || StringUtils.isEmpty(xsmc)){
                return new ResultInfo(500,"录入信息丢失！",null);
            }

            if (jsonObject.containsKey("nonce_ms")) {
                nonce_ms = jsonObject.getString("nonce_ms");
            }
            if (jsonObject.containsKey("nonce_zhi")) {
                nonce_zhi = jsonObject.getString("nonce_zhi");
            }

            //校验nonce
            ResultInfo ResultInfoCheckNonce = new ResultInfo();
            ResultInfoCheckNonce = tApiNonceService.checkNonce(nonce_ms,loginId,nonce_zhi,"stampxm.save");

            if (ResultInfoCheckNonce.getCode()!=200)
            {
                return ResultInfoCheckNonce;
            }

            TCzy tCzy = gettCzyDao().getCzyById(loginId);

            StampXm stampXm = new StampXm();
            if ("1".equals(lx)){
                if(StringUtils.isEmpty(id)){
                    return new ResultInfo(500,"修改信息丢失！",null);
                }
                try {
                    id = Url.decrypt(id);
                } catch (Exception e) {
                    throw new RuntimeException("修改信息丢失！");
                }
                stampXm = stampXmMapper.selectById(id);

                if(!stampXm.getTCzyId().equals(tCzy.getId())){
                    return new ResultInfo(500,"只支持自己修改自己建立的项目！",null);
                }
            }
            stampXm.setXsmc(xsmc);
            stampXm.setName(xmmc);
            stampXm.setZjm(ToolBean.getPy(xmmc));
            stampXm.setTCzyId(tCzy.getId());
            stampXm.setTXzjgId(tCzy.getXzjgId());
            if ("1".equals(lx)){
                //修改的时候，文件上传变更
                String lj = "";
                String os = System.getProperty("os.name");
                if (os != null && os.contains("Windows")) {
                    lj = "d:\\stamp\\xm\\" + stampXm.getId()+"\\";
                } else {
                    //linux
                    lj = "/home/stamp/xm/"+stampXm.getId()+"/";
                }
                String text = wdpz.getYm() + "h5/myhome/index?id=" + ToolBean.getEncode(stampXm.getId());
                //准备生成二维码图片
                try{
                    QRCodeGenerator.generateQRCodeImage(text, 400, 400, lj,stampXm.getId() + "_qr.png");
                }catch (Exception e){
                    return new ResultInfo(500,"活动二维码生成错误！",null);
                }
                //上传文件
                if (null!=file){
                    for (MultipartFile wj : file) {

                        if (StringUtils.isEmpty(wj.getOriginalFilename())){
                            continue;
                        }
                        fileService.uploadFileToLj(wj,lj,stampXm.getId() + "_bjtp.png");
                    }
                }
                stampXmMapper.updateById(stampXm);
                return new ResultInfo(0,"操作成功！",null);
            }else{
                stampXmMapper.insert(stampXm);
                stampXm.setQrcode(stampXm.getId()+ "_qr.png");
                stampXm.setBjtp(stampXm.getId()+ "_bjtp.png");
                String lj = "";
                String os = System.getProperty("os.name");
                if (os != null && os.contains("Windows")) {
                    lj = "d:\\stamp\\xm\\" + stampXm.getId()+"\\";
                } else {
                    //linux
                    lj = "/home/stamp/xm/"+stampXm.getId()+"/";
                }
                String text = wdpz.getYm() + "h5/myhome/index?id=" + ToolBean.getEncode(stampXm.getId());
                //准备生成二维码图片
                try{
                    QRCodeGenerator.generateQRCodeImage(text, 400, 400, lj,stampXm.getId() + "_qr.png");
                }catch (Exception e){
                    return new ResultInfo(500,"活动二维码生成错误！",null);
                }
                //上传文件
                if (null!=file){
                    for (MultipartFile wj : file) {

                        if (StringUtils.isEmpty(wj.getOriginalFilename())){
                            continue;
                        }
                        fileService.uploadFileToLj(wj,lj,stampXm.getId() + "_bjtp.png");
                    }
                }
                stampXmMapper.updateById(stampXm);
                return new ResultInfo(0,"操作成功！",null);
            }
        }
    }

    @Override
    @Transactional
    public ResultInfo del(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String ids = "";
            if (jsonObject.containsKey("ids")) {
                ids = jsonObject.getString("ids");
            }
            String [] code = ids.split(",");
            int i=0;
            String str="";

            TCzy tCzy = gettCzyDao().getCzyById(loginId);
            StampXm stampXm = new StampXm();

            for(i=0;i<code.length;i++)
            {
                if (code[i].equals("")) {
                    continue;
                }
                String id = null;
                try {
                    ToolBean.info("code[i]准备解密："+code[i]);
                    id = Url.decrypt(java.net.URLDecoder.decode(code[i],"utf-8"));
                    ToolBean.info("code[i]准备解密后："+id);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("");
                }

                stampXm = new StampXm();
                stampXm = stampXmMapper.selectById(id);

                //项目经理和操作员职工信息一致的，才能删除！
                if (!stampXm.getTCzyId().equals(tCzy.getId())){
                    str+=stampXm.getName()+"[非本人建立的项目，无法删除]，";
                    continue;
                }

                //如果项目没有任何动态信息，直接连软件信息一起删除！
                long sl1 = stampHdMapper.selectCount(new QueryWrapper<StampHd>().eq("xm_id",id));
                if (sl1>0) {
                    str+=stampXm.getName()+"，";
                    continue;
                }
                String lj="";
                try {
                    String os = System.getProperty("os.name");
                    lj="";
                    if (os != null && os.contains("Windows")) {
                        lj = "d:\\stamp\\xm\\" + stampXm.getId()+"\\";
                    } else {
                        //linux
                        lj = "/home/stamp/xm/"+stampXm.getId()+"/";
                    }
                    TDel tDel = new TDel();
                    tDel.setLj(lj);
                    tDel.setLx("2");
                    tDelDao.insert(tDel);
                    File directory = new File(lj);
                    if (directory.exists()){
                        File[] files = directory.listFiles();
                        if (files != null) {
                            for (File file : files) {
                                file.delete();
                            }
                        }
                        // 删除空文件夹
                        directory.delete();
                    }
                    stampXmMapper.deleteById(id);
                }catch (Exception e){
                    ToolBean.info("StampHdServices.del文件目录["+lj+"]删除发生错误："+e.toString());
                    continue;
                }

            }
            ResultInfo resultInfo;
            if (str.length()>0) {
                str = str.substring(0,str.length()-1);
            }
            if (!StringUtils.isEmpty(str))
            {
                str="["+str+"]包含活动信息，无法删除！";
                resultInfo = new ResultInfo(500, str,null);
            }
            else {
                resultInfo = new ResultInfo(0, str,null);
            }
            return backRtn(resultInfo,loginId);
        }
    }
}
